package com.zhuhjay.boot.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zhuhjay.domain.entity.Permission;
import com.zhuhjay.domain.entity.Role;
import com.zhuhjay.domain.entity.User;
import com.zhuhjay.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 用户登录的服务实现类
 * @author ZhuHJay
 * @date 2022/4/4 14:22
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取用户的信息(包括所有权限角色信息)
        User user = userService.findAllTableByUsername(username);
        if( user == null ){
            // 用户名不存在
            return null;
        }

        List<GrantedAuthority> authorities = new ArrayList<>();

        // 动态授权
        Set<Role> roles = user.getRoles();
        roles.forEach(role -> {
            // 角色授予
            authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            permissions.forEach(permission -> {
                // 权限授权
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            });
        });

        return org.springframework.security.core.userdetails.User.builder()
                .username(username)
                .password(user.getPassword())
                // 授权
                .authorities(authorities)
                .build();
    }

}
